<!-- 积分订单页面 -->
<template>
  <s-layout title="积分订单">
    <su-sticky bgColor="#fff">
      <su-tabs
        :list="tabMaps"
        :scrollable="false"
        @change="onTabsChange"
        :current="state.currentTab"
      ></su-tabs>
    </su-sticky>
    
    <s-empty
      v-if="state.pagination.total === 0"
      icon="/static/order-empty.png"
      text="暂无积分订单"
    ></s-empty>
    
    <view v-if="state.pagination.total > 0">
      <view
        class="bg-white order-list-card-box ss-r-10 ss-m-t-14 ss-m-20"
        v-for="order in state.pagination.data"
        :key="order.id"
        @tap="onOrderDetail(order.order_sn)"
      >
        <view class="order-card-header ss-flex ss-col-center ss-row-between ss-p-x-20">
          <view class="order-no">订单号：{{ order.order_sn }}</view>
          <view class="order-state ss-font-26" :class="formatOrderColor(order.status_code)">
            {{ order.status_text }}
          </view>
        </view>
        
        <view class="border-bottom" v-for="item in order.items" :key="item.id">
          <s-goods-item
            :img="item.goods_image"
            :title="item.goods_title"
            :skuText="item.goods_sku_text"
            :price="item.goods_price"
            :score="order.score_amount"
            :num="item.goods_num"
          >
            <template #tool>
              <view class="ss-flex">
                <button
                  class="ss-reset-button apply-btn"
                  v-if="item.btns.includes('aftersale')"
                  @tap.stop="
                    sheep.$router.go('/pages/order/aftersale/apply', {
                      item: JSON.stringify(item),
                    })
                  "
                >
                  申请售后
                </button>
                <button
                  class="ss-reset-button apply-btn"
                  v-if="item.btns.includes('buy_again')"
                  @tap.stop="
                    sheep.$router.go('/pages/goods/score', {
                      id: item.goods_id,
                    })
                  "
                >
                  再次兑换
                </button>
              </view>
            </template>
          </s-goods-item>
        </view>
        
        <view class="pay-box ss-m-t-30 ss-flex ss-row-right ss-p-r-20">
          <view v-if="order.total_discount_fee > 0" class="ss-flex ss-col-center ss-m-r-8">
            <view class="discounts-title">优惠:￥</view>
            <view class="discounts-money">{{ order.total_discount_fee }}</view>
          </view>
          <view class="ss-flex ss-col-center ss-m-r-8">
            <view class="discounts-title">运费:￥</view>
            <view class="discounts-money">{{ order.dispatch_amount }}</view>
          </view>
          <view class="ss-flex ss-col-center">
            <view class="discounts-title pay-color">总金额:</view>
            <view class="discounts-money pay-color">￥{{ order.order_amount }}</view>
            <view v-if="order.score_amount">+</view>
            <view class="discounts-money pay-color ss-flex ss-col-center" v-if="order.score_amount">
              <image
                :src="sheep.$url.static('/assets/addons/shopro/uniapp/goods/score1.svg')"
                class="score-img"
              ></image>
              <view>{{ order.score_amount }}</view>
            </view>
          </view>
        </view>
        
        <view class="order-card-footer ss-flex ss-col-center ss-p-x-20">
          <view class="ss-flex ss-col-center">
            <button
              v-if="order.btns.includes('confirm')"
              class="tool-btn ss-reset-button"
              @tap.stop="onConfirm(order)"
            >
              确认收货
            </button>
            <button
              v-if="order.btns.includes('express')"
              class="tool-btn ss-reset-button"
              @tap.stop="onExpress(order.id)"
            >
              查看物流
            </button>
            <button
              v-if="order.btns.includes('comment')"
              class="tool-btn ss-reset-button"
              @tap.stop="onComment(order.order_sn)"
            >
              评价晒单
            </button>
            <button
              v-if="order.btns.length === 0"
              class="tool-btn ss-reset-button"
              @tap.stop="onOrderDetail(order.order_sn)"
            >
              查看详情
            </button>
          </view>
        </view>
      </view>
    </view>
    
    <uni-load-more
      v-if="state.pagination.total > 0"
      :status="state.loadStatus"
      :content-text="{
        contentdown: '上拉加载更多',
      }"
      @tap="loadmore"
    />
  </s-layout>
</template>

<script setup>
  import { computed, reactive } from 'vue';
  import { onLoad, onReachBottom, onPullDownRefresh } from '@dcloudio/uni-app';
  import { formatOrderColor } from '@/sheep/hooks/useGoods';
  import sheep from '@/sheep';
  import _ from 'lodash';

  const pagination = {
    data: [],
    current_page: 1,
    total: 1,
    last_page: 1,
  };

  const state = reactive({
    currentTab: 0,
    pagination: {
      data: [],
      current_page: 1,
      total: 1,
      last_page: 1,
    },
    loadStatus: '',
  });

  const tabMaps = [
    {
      name: '全部',
      value: 'all',
    },
    {
      name: '待付款',
      value: 'unpaid',
    },
    {
      name: '待发货',
      value: 'nosend',
    },
    {
      name: '待收货',
      value: 'noget',
    },
    {
      name: '待评价',
      value: 'nocomment',
    },
  ];

  // 切换选项卡
  function onTabsChange(e) {
    if (state.currentTab === e.index) return;
    state.pagination = pagination;
    state.currentTab = e.index;
    getScoreOrderList();
  }

  // 订单详情
  function onOrderDetail(orderSN) {
    sheep.$router.go('/pages/order/detail', {
      orderSN,
    });
  }

  // 确认收货
  async function onConfirm(order) {
    const { code, data } = await sheep.$api.order.confirm(order.id);
    if (code === 1) {
      state.pagination = pagination;
      getScoreOrderList();
    }
  }

  // 查看物流
  function onExpress(orderId) {
    sheep.$router.go('/pages/order/express/list', {
      orderId,
    });
  }

  // 评价
  function onComment(orderSN) {
    sheep.$router.go('/pages/goods/comment/add', {
      orderSN,
    });
  }

  // 获取积分订单列表
  async function getScoreOrderList(page = 1, list_rows = 5) {
    state.loadStatus = 'loading';
    let res = await sheep.$api.order.list({
      type: tabMaps[state.currentTab].value,
      list_rows,
      page,
      order_type: 'score', // 只获取积分订单
    });
    
    if (res.code === 1) {
      let orderList = _.concat(state.pagination.data, res.data.data);
      state.pagination = {
        ...res.data,
        data: orderList,
      };

      if (state.pagination.current_page < state.pagination.last_page) {
        state.loadStatus = 'more';
      } else {
        state.loadStatus = 'noMore';
      }
    }
  }

  onLoad(async (options) => {
    if (options.type) {
      state.currentTab = options.type;
    }
    getScoreOrderList();
  });

  // 加载更多
  function loadmore() {
    if (state.loadStatus !== 'noMore') {
      getScoreOrderList(state.pagination.current_page + 1);
    }
  }

  // 上拉加载更多
  onReachBottom(() => {
    loadmore();
  });

  // 下拉刷新
  onPullDownRefresh(() => {
    state.pagination = pagination;
    getScoreOrderList();
    setTimeout(function () {
      uni.stopPullDownRefresh();
    }, 800);
  });
</script>

<style lang="scss" scoped>
  .score-img {
    width: 36rpx;
    height: 36rpx;
    margin: 0 4rpx;
  }
  
  .tool-btn {
    width: 160rpx;
    height: 60rpx;
    background: #f6f6f6;
    font-size: 26rpx;
    border-radius: 30rpx;
    margin-right: 10rpx;

    &:last-of-type {
      margin-right: 0;
    }
  }

  .apply-btn {
    width: 140rpx;
    height: 50rpx;
    border-radius: 25rpx;
    font-size: 24rpx;
    border: 2rpx solid #dcdcdc;
    line-height: normal;
    margin-left: 16rpx;
  }

  .order-list-card-box {
    margin: 20rpx;
    border-radius: 16rpx;
    overflow: hidden;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
  }

  .order-card-header {
    padding: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .order-no {
      font-size: 26rpx;
      color: #666;
    }
    
    .order-state {
      font-weight: 500;
      
      &.status-unpaid {
        color: #ff6600;
      }
      
      &.status-nosend {
        color: #007aff;
      }
      
      &.status-noget {
        color: #ff6600;
      }
      
      &.status-nocomment {
        color: #ff6600;
      }
      
      &.status-completed {
        color: #52c41a;
      }
      
      &.status-cancelled {
        color: #999;
      }
    }
  }

  .border-bottom {
    border-bottom: 1rpx solid #f5f5f5;
  }

  .pay-box {
    padding: 20rpx;
    border-bottom: 1rpx solid #f5f5f5;
    
    .discounts-title {
      font-size: 26rpx;
      color: #666;
    }
    
    .discounts-money {
      font-size: 26rpx;
      color: #333;
      font-weight: 500;
      
      &.pay-color {
        color: #ff6600;
        font-weight: 600;
      }
    }
  }

  .order-card-footer {
    padding: 20rpx;
  }
</style>
